package cn.com.connext.scrm.service;

import cn.com.connext.scrm.domain.master.DrawActivity;
import cn.com.connext.scrm.domain.master.PrizeGood;
import cn.com.connext.scrm.domain.master.WriteOffCode;
import cn.com.connext.scrm.domain.master.WriteOffRecord;
import cn.com.connext.scrm.repository.master.DrawActivityRepository;
import cn.com.connext.scrm.repository.master.PrizeGoodRepository;
import cn.com.connext.scrm.repository.master.WriteOffRecordRepository;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.service.dto.WriteOffRecordDTO;
import cn.com.connext.scrm.web.rest.WriteOffRecordResource;
import cn.com.connext.scrm.web.rest.vm.WriteOffRecordExcelVm;
import cn.com.connext.scrm.web.rest.vm.WriteOffRecordPageVM;
import cn.com.connext.scrm.web.rest.vm.WriteOffRecordVM;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Service
@Transactional
public class WriteOffRecordService {
    private final Logger logger = LoggerFactory.getLogger(WriteOffRecordResource.class);
    @Autowired
    private WriteOffRecordRepository writeOffRecordRepository;
    @Autowired
    private WriteOffCodeService writeOffCodeService;

    @Autowired
    private PrizeGoodRepository prizeGoodRepository;

    @Autowired
    private DrawActivityRepository drawActivityRepository;

    @Autowired
    private WriteOffRecordMapper mapper;

    public JsonResult save(WriteOffRecordVM vm) {
        JsonResult jsonResult =new JsonResult();
       try {
           logger.info("核销记录：{}", vm.toString());
           if (vm != null) {
               WriteOffRecord entity = new WriteOffRecord();
               BeanUtils.copyProperties(vm, entity);
               entity.setCreateTime(ZonedDateTime.now());
               writeOffRecordRepository.saveAndFlush(entity);
               jsonResult.setState(0);
               jsonResult.setMessage("核销记录添加成功");
           }else{
               jsonResult.setState(-1);
               jsonResult.setMessage("核销记录添加失败,参数不能为空!");
           }
       }catch (Exception e){
           jsonResult.setState(-1);
           jsonResult.setMessage("系统异常,核销失败");
           logger.error("异常信息：{}",e.getMessage());
       }
       return jsonResult;
    }

    public Page<WriteOffRecordDTO> findByPage(WriteOffRecordPageVM worm) {
        PageRequest pageRequest = new PageRequest(worm.getPage(), worm.getPageSize(), Sort.Direction.DESC, "createTime");
        Page<WriteOffRecord> page = writeOffRecordRepository.findAll(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                List<Predicate> list = new LinkedList<>();
                if (StringUtils.isNotEmpty(worm.getActivityId())) {
                    Predicate activityName = cb.equal(root.get("activityId"), worm.getActivityId());
                    list.add(activityName);
                }
//                if (StringUtils.isNotEmpty(worm.getPrizeGoodName())) {
//                    List<Integer>  prizeGoodIds= prizeGoodRepository.findAllPrizeGoodNameLikeThis(worm.getPrizeGoodName());
//                    Predicate prizeGoodId = cb.equal(root.get("prizeGoodId"), prizeGoodIds);
//                    list.add(prizeGoodId);
//                }
                Predicate[] pre = new Predicate[list.size()];
                return query.where(list.toArray(pre)).getRestriction();
            }
        }, pageRequest);
        Page<WriteOffRecordDTO> dtoPage = page.map(i -> {
            WriteOffRecordDTO writeOffRecordDTO = mapper.toDto(i);
            if(writeOffRecordDTO.getPrizeGoodId()!=null){
                PrizeGood good = prizeGoodRepository.findOne(writeOffRecordDTO.getPrizeGoodId());
                if(good !=null) {
                    writeOffRecordDTO.setPrizeGoodName(good.getGoodName());
                }
            }
            if(writeOffRecordDTO.getPrizeGoodId()!=null){
                DrawActivity activity = drawActivityRepository.findOne(writeOffRecordDTO.getActivityId());
                if(activity !=null) {
                    writeOffRecordDTO.setActivityName(activity.getActivityName());
                }
            }
            if(writeOffRecordDTO.getWriteOffCodeId()!=null){
                WriteOffCode woc = writeOffCodeService.findById(writeOffRecordDTO.getWriteOffCodeId());
                if(woc !=null) {
                    writeOffRecordDTO.setWriteOffUser(woc.getWriteOffUser());
                }
            }
            return writeOffRecordDTO;
        });
        return dtoPage;
    }

    public List<WriteOffRecordExcelVm> findAll(WriteOffRecordPageVM worm) {
        List<WriteOffRecord> list =null;
        if(worm !=null && StringUtils.isNotEmpty(worm.getActivityId())){
            list = writeOffRecordRepository.findByActivityId(worm.getActivityId());
        }else{
            list = writeOffRecordRepository.findAll();
        }
        List<WriteOffRecordExcelVm> vmList= new ArrayList<>();
        DateTimeFormatter beijingFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("Asia/Shanghai"));
        if(list !=null && list.size() >0){
            WriteOffRecordExcelVm vm =null;
            for (WriteOffRecord record:list ) {
                vm =new WriteOffRecordExcelVm();
                BeanUtils.copyProperties(record,vm);
                if(record.getCreateTime() !=null){
                    String nowTimeStr = beijingFormatter.format(record.getCreateTime());
                    vm.setCreateTime(nowTimeStr);
                }
                if(record.getPrizeGoodId()!=null){
                    PrizeGood good = prizeGoodRepository.findOne(record.getPrizeGoodId());
                    if(good !=null) {
                        vm.setPrizeGoodName(good.getGoodName());
                    }
                }
                if(record.getPrizeGoodId()!=null){
                    DrawActivity activity = drawActivityRepository.findOne(record.getActivityId());
                    if(activity !=null) {
                        vm.setActivityName(activity.getActivityName());
                    }
                }
                if(record.getWriteOffCodeId()!=null){
                    WriteOffCode woc = writeOffCodeService.findById(record.getWriteOffCodeId());
                    if(woc !=null) {
                        vm.setWriteOffUser(woc.getWriteOffUser());
                    }
                }
                vmList.add(vm);
            }
        }
        return vmList;
    }
}
